package jh.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.jh.ios.forecast.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jh.adapter.LotteryAdapter;
import jh.model.MModel;
import jh.utils.HttpUtils;

public class HsitoryActivity extends BaseActivity {

    private String titleString;
    private ListView listView;
    private LotteryAdapter adapter;
    private String code;
    private List<MModel> list = new ArrayList<>();
    private ProgressBar progressBar;
    @Override
    public int getLayoutId() {
        return R.layout.activity_history;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        titleString = getIntent().getStringExtra("title");
        code = getIntent().getStringExtra("code");
        getData();
    }

    @Override
    public void initView() {
        backButton = find(R.id.back_buton);
        showBackButton();

        title = find(R.id.navigation_title);
        title.setText(titleString);

        progressBar = find(R.id.progressBar);

        listView = find(R.id.list_view);
        adapter = new LotteryAdapter(this,list,true);
        listView.setAdapter(adapter);

    }

    private void getData(){


        String url = "/api/lotteryOpenNumber/getNewestOpenNumberByLotteryCategory";

        Map<String,String> map = new HashMap<>();
        map.put("lotteryCategoryCode",code);
        map.put("number","100");

        HttpUtils.POST(url, map, new HttpUtils.HttpResponse() {
            @Override
            public void callback(JSONObject object, String msg, Exception e) {
                listView.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
                if (e == null){
                    if (msg == null){
                        Log.i("json == ",object.toString());
                        JSONArray jsonArray = null;
                        try {
                            list.clear();
                            jsonArray = object.getJSONArray("data");
                            GsonBuilder builder = new GsonBuilder();
                            Gson gson = builder.create();
                            List<MModel> array = gson.fromJson(jsonArray.toString(),new TypeToken<List<MModel>>(){}.getType());

                            list.addAll(array);
                            adapter.notifyDataSetChanged();

                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        });
    }




}
